package com.ict.web.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.core.domain.AjaxResult;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.service.ISysDictDataService;
import com.ict.web.constant.ProjectInfoConstants;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.ProjectInfo;
import com.ict.web.domain.ProjectManagement;
import com.ict.web.domain.ProjectSystemInfo;
import com.ict.web.domain.SchemeDeclaration;
import com.ict.web.dto.ExportProjectInfo;
import com.ict.web.dto.GetProjectInfoListDto;
import com.ict.web.dto.GetProjectInfoListRespDto;
import com.ict.web.dto.ImportProjectInfoDto;
import com.ict.web.mapper.ProjectInfoMapper;
import com.ict.web.service.IProjectManagementService;
import com.ict.web.service.ISchemeDeclarationService;
import com.ict.web.service.ProjectInfoService;
import com.ict.web.vo.req.GetProjectInfoListReq;
import com.ict.web.vo.req.SaveProjectInfoReq;
import com.ict.web.vo.req.UpdateProjectInfoReq;
import com.ict.web.vo.resp.GetProjectInfoListResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class ProjectInfoServiceImpl extends ServiceImpl<ProjectInfoMapper, ProjectInfo> implements ProjectInfoService {

    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IProjectManagementService projectManagementService;

    @Autowired
    private ISchemeDeclarationService schemeDeclarationService;

    @Autowired
    private IYzqFileService fileService;
    /**
     * 新增项目
     *
     * @param req
     * @return
     */
    @Override
    public AjaxResult saveProjectInfo(SaveProjectInfoReq req) {
        ProjectInfo projectInfo = new ProjectInfo();
        BeanUtils.copyProperties(req, projectInfo);
        projectInfo.setProId(IdUtil.getSnowflakeNextIdStr());
        save(projectInfo);
        return AjaxResult.success("新增成功!");
    }

    /**
     * 删除项目
     *
     * @param proId
     * @return
     */
    @Override
    public AjaxResult deletePorjectInfo(String proId) {
        if (StrUtil.isNotBlank(proId)) {
            baseMapper.deleteById(proId);
            return AjaxResult.success("删除成功!");
        }
        return AjaxResult.error("项目Id不能为空!");
    }

    /**
     * 修改项目
     *
     * @param req
     * @return
     */
    @Override
    public AjaxResult updatePorjectInfo(UpdateProjectInfoReq req) {
        ProjectInfo projectInfo = getById(req.getProId());
        if (projectInfo != null) {
            BeanUtils.copyProperties(req, projectInfo);
            projectInfo.setUpdateTime(LocalDateTime.now());
            updateById(projectInfo);
            return AjaxResult.success("修改成功!");
        }
        return AjaxResult.error("项目信息不存在!");
    }

    /**
     * 查询项目列表
     *
     * @param req
     * @return
     */
    @Override
    public List<GetProjectInfoListResp> getProjectInfoList(GetProjectInfoListReq req) {
        List<GetProjectInfoListDto> dto = projectInfoMapper.getProjectInfoList(req);
        List<GetProjectInfoListResp> resps = Collections.EMPTY_LIST;
        if (!CollectionUtils.isEmpty(dto)) {
            resps = dto.stream().map(o -> getGetProjectInfoListResp(o)).collect(Collectors.toList());
        }
        return resps;
    }

    /**
     * 项目列表抽取业务方法
     *
     * @param o
     * @return
     */
    private GetProjectInfoListResp getGetProjectInfoListResp(GetProjectInfoListDto o) {
        GetProjectInfoListResp resp = new GetProjectInfoListResp();
        ProjectInfo info = new ProjectInfo();
        BeanUtils.copyProperties(o, info);
        info.setProNature(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NATURE).get(o.getProNature()))
//                .setProStag(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_STAG).get(o.getProStag()))
//                .setProNode(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NODE).get(o.getProNode()))
                .setProType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProType()))
                .setProState(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProState()));
        resp.setProjectInfo(info);
        ProjectSystemInfo systemInfo = new ProjectSystemInfo();
        BeanUtils.copyProperties(o, systemInfo);
        systemInfo.setIfUnifiedPortal(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_IFUNIFIEDPORTAL).get(o.getIfUnifiedPortal()))
                .setNetworkType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_NETWORKTYPE).get(o.getNetworkType()));
        resp.setProjectSystemInfo(systemInfo);
        //增加项目初设方案id
        List<YzqFile> fileList = fileService.lambdaQuery().eq(YzqFile::getRelationId, systemInfo.getProId()).list();
        if(StringUtils.isNotEmpty(fileList)){
            resp.setFile(fileList.get(0));
        }
        return resp;
    }

    @Override
    public Boolean saveProjectInfoList(List<ImportProjectInfoDto> list) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
        List<ProjectInfo> projectInfos = list.stream().map(o -> {
            ProjectInfo projectInfo = new ProjectInfo();
            BeanUtils.copyProperties(o, projectInfo);
            projectInfo.setProTime(LocalDateTime.parse(o.getProTime(), formatter))
                    .setUpdateTime(LocalDateTime.parse(o.getUpdateTime(), formatter));
            return projectInfo;
        }).collect(Collectors.toList());
        saveBatch(projectInfos);
        return true;
    }


    @Override
    public List<ExportProjectInfo> getProjectInfoListByIds(List<String> ids) {
        List<GetProjectInfoListDto> dtos = projectInfoMapper.getProjectInfoListByIds(ids);
        List<ExportProjectInfo> exports = new ArrayList<>();
        for (GetProjectInfoListDto o : dtos) {
            ExportProjectInfo info = new ExportProjectInfo();
            BeanUtils.copyProperties(o, info);
            info.setProNature(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NATURE).get(o.getProNature()))
//                    .setProStag(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_STAG).get(o.getProStag()))
//                    .setProNode(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NODE).get(o.getProNode()))
                    .setProType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProType()))
                    .setProState(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProState()));
            //屏蔽系统枚举值转化
//                    .setAppIsCloud(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_ISCLOUD).get(o.getAppIsCloud().toString()))
//                    .setIfUnifiedPortal(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_IFUNIFIEDPORTAL).get(o.getIfUnifiedPortal()))
//                    .setNetworkType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_NETWORKTYPE).get(o.getNetworkType()));
            exports.add(info);
        }
        return exports;
    }
    @Override
    public List<GetProjectInfoListRespDto> getProjectApprovalInfoList(GetProjectInfoListReq req) {
        List<GetProjectInfoListRespDto> dto = projectInfoMapper.getProjectApprovalInfoList(req);
//        if (!CollectionUtils.isEmpty(dto)) {
//            for (GetProjectInfoListRespDto o : dto) {
//                o.setProNature(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NATURE).get(o.getProNature()))
//                        .setProStag(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_STAG).get(o.getProStag()))
//                        .setProNode(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NODE).get(o.getProNode()))
//                        .setProType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProType()))
//                        .setProState(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProState()));
//                if(StringUtils.isNotEmpty(o.getProjectSystemInfoList())){
//                    for(ProjectSystemInfo s:o.getProjectSystemInfoList()){
//                        s.setIfUnifiedPortal(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_IFUNIFIEDPORTAL).get(s.getIfUnifiedPortal()))
//                                .setNetworkType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_NETWORKTYPE).get(s.getNetworkType()))
//                                .setAppIsCloud(Boolean.parseBoolean(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_SYS_ISCLOUD).get(s.getAppIsCloud().toString())));
//                    }
//                }
//            }
//        }
        return dto;
    }
    /**
     * 导出全部数据
     *
     * @param req
     * @return
     */
    @Override
    public List<GetProjectInfoListResp> getProjectInfoAll() {
        List<ProjectInfo> dto = projectInfoMapper.selectList(new QueryWrapper<ProjectInfo>(null).orderByDesc("pro_time"));
        List<GetProjectInfoListResp> resps = Collections.EMPTY_LIST;
        if (!CollectionUtils.isEmpty(dto)) {
            resps = dto.stream().map(o -> getGetProjectInfoList(o)).collect(Collectors.toList());
        }
        return resps;
    }

    @Override
    public boolean upload(YzqFile file, Long proId) {
        boolean t=true;
        ProjectManagement projectManagement = projectManagementService.getById(proId);
        //新增项目
        if (StringUtils.isNotNull(projectManagement)) {
            SchemeDeclaration schemeDeclaration = schemeDeclarationService.getById(projectManagement.getProgrammeId());
            List<YzqFile> fileList = fileService.lambdaQuery().eq(YzqFile::getRelationId, proId).list();
            //新增文件
            if(StringUtils.isEmpty(fileList)){
                file.setId(String.valueOf(IdUtils.snowId()));
                file.setRelationId(String.valueOf(proId));
                t=fileService.save(file);
            //修改文件
            }else {
                YzqFile yzqFile = fileList.get(0);
                file.setId(yzqFile.getId());
                BeanUtils.copyProperties(file,yzqFile);
                t=fileService.updateById(yzqFile);
            }
            //存量项目
        }else {
            List<YzqFile> fileList = fileService.lambdaQuery().eq(YzqFile::getRelationId, proId).list();
            if(StringUtils.isEmpty(fileList)){
                file.setId(String.valueOf(IdUtils.snowId()));
                file.setRelationId(String.valueOf(proId));
                t=fileService.save(file);

            }else {
                YzqFile yzqFile = fileList.get(0);
                file.setId(yzqFile.getId());
                BeanUtils.copyProperties(file,yzqFile);
                t=fileService.updateById(yzqFile);
            }
        };
        return t;
    }

    private GetProjectInfoListResp getGetProjectInfoList(ProjectInfo o) {
        GetProjectInfoListResp resp = new GetProjectInfoListResp();
        ProjectInfo info = new ProjectInfo();
        BeanUtils.copyProperties(o, info);
        info.setProNature(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NATURE).get(o.getProNature()))
//                .setProStag(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_STAG).get(o.getProStag()))
//                .setProNode(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_NODE).get(o.getProNode()))
                .setProType(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProType()))
                .setProState(dictDataService.getDictDataByDictType(ProjectInfoConstants.PRO_TYPE).get(o.getProState()));
        resp.setProjectInfo(info);
        ProjectSystemInfo systemInfo = new ProjectSystemInfo();
        return resp;
    }
}
